
#include "screenTimeManager.h"

ScreenTimeManager::ScreenTimeManager(QObject *parent)
    : QObject(parent),
      m_timer(new QTimer(this)),
      m_usedSeconds(0),
      m_dailyLimitSeconds(8 * 3600), // 默认每日限制为 8 小时
      m_alertThreshold(90) {        // 默认提醒阈值为 90%
    
    // 设置定时器，每秒更新一次时间
    connect(m_timer, &QTimer::timeout, this, [this]() {
        m_usedSeconds++;
        emit timeUpdated();
        checkThreshold();
    });
    m_timer->start(1000); // 每秒触发
}

ScreenTimeManager::~ScreenTimeManager() {
    if (m_timer) {
        m_timer->stop();
        delete m_timer;
    }
}

QString ScreenTimeManager::usedTime() const {
    int hours = m_usedSeconds / 3600;
    int minutes = (m_usedSeconds % 3600) / 60;
    return QString("%1:%2").arg(hours, 2, 10, QChar('0')).arg(minutes, 2, 10, QChar('0'));
}

int ScreenTimeManager::usedPercentage() const {
    return static_cast<int>((static_cast<double>(m_usedSeconds) / m_dailyLimitSeconds) * 100);
}

void ScreenTimeManager::resetUsage() {
    m_usedSeconds = 0;
    emit timeUpdated();
}

void ScreenTimeManager::checkThreshold() {
    if (usedPercentage() >= m_alertThreshold) {
        emit alertThresholdReached();
    }
}
